<script setup lang="ts">
import { ElMessage } from "element-plus";
import { computed, onMounted, ref, watch } from "vue";
import * as XLSX from "xlsx";
import CupAttributeList from "./data/CupAttribute.json";
import headAttributeList from "./data/HeadAttribute.json";
// 2025-10-24  6.1版本，一共105个角色
import RolesList from "./data/Roles.json";
import SacredRelicList from "./data/SacredRelic.json";
import SandAttributeList from "./data/SandAttribute.json";
import SubAttributeList from "./data/SubAttribute.json";
import tableDataOrigin from "./data/tableData.json";
import "./index.css";

const fromParams = ref({
  role: undefined,
  type: "",
  SacredRelicId: undefined,
  sand: undefined,
  cup: undefined,
  head: undefined,
  SubAttribute: undefined,
  NoSubAttribute: undefined
});

const fileEleRef = ref();
const roleType = ref();
const TypeList = ref([
  { value: "雷", label: "雷" },
  { value: "水", label: "水" },
  { value: "风", label: "风" },
  { value: "火", label: "火" },
  { value: "岩", label: "岩" },
  { value: "冰", label: "冰" },
  { value: "草", label: "草" }
]);

const TypeListColor = ref({
  水: "text-blue",
  火: "text-red",
  雷: "text-dark-blue",
  冰: "text-green",
  岩: "text-orange",
  风: "text-cyan",
  草: "text-purple"
});

const colorList = ref([
  "text-black",
  "text-dark-gray",
  "text-gray",
  "text-light-gray",
  "text-blue",
  "text-red",
  "text-dark-blue",
  "text-green",
  "text-orange",
  "text-cyan",
  "text-purple",
  "text-blue-all"
]);

const headColorList = ref(["text-black", "text-dark-gray", "text-gray", "text-light-gray", "text-blue", "text-red", "text-red02", "text-red03"]);
const subColorList = ref([
  "text-black",
  "text-dark-gray",
  "text-gray",
  "text-light-gray",
  "text-blue",
  "text-red",
  "text-red02",
  "text-black-opicity",
  "text-dark-gray-opicity",
  "text-gray-opicity"
]);

// ==================== 分页相关 ====================
const currentPage = ref(1);
const pageSize = ref(12);
const dialogTableVisible = ref(false);

// 当前显示的数据
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// =================================================

const clearAll = () => {
  fromParams.value = {
    role: undefined,
    type: "",
    SacredRelicId: undefined,
    sand: undefined,
    cup: undefined,
    head: undefined,
    SubAttribute: undefined,
    NoSubAttribute: undefined
  };
  tableData.value = tableDataOrigin;
  currentPage.value = 1; // 回到第一页
};

watch(
  fromParams,
  () => {
    search();
  },
  { deep: true }
);

const tableData = ref([]);

const search = () => {
  tableData.value = tableDataOrigin.filter(item => {
    const { role, type, SacredRelicId, sand, cup, head, SubAttribute, NoSubAttribute } = fromParams.value;

    // 主筛选条件
    const match =
      (!role?.length || role.includes(item.name)) &&
      (!type || item.roleType === type) &&
      (!SacredRelicId || item.SacredRelicId === SacredRelicId) &&
      (!sand || item.Sand === sand) &&
      (!cup || item.cup === cup) &&
      (!head || item.head === head) &&
      (!SubAttribute?.length || SubAttribute.every(sub => item.SubAttribute.includes(sub)));

    // 排除副词条逻辑
    const noSubExclude = !NoSubAttribute?.length || !NoSubAttribute.some(noSub => item.SubAttribute.includes(noSub));

    return match && noSubExclude;
  });

  currentPage.value = 1;
};

const parsedData = ref([]); // 存放解析后的 JSON 数据
const sortedEntriesData = ref([]); // 存放解析后的 JSON 数据

const onFileChange = event => {
  const file = event.target.files?.[0];
  if (!file) return;

  const reader = new FileReader();
  // 可以用 arrayBuffer、binary 或者其他方式
  reader.onload = e => {
    const data = e.target.result;
    // 这里假设用 arrayBuffer
    const workbook = XLSX.read(data, { type: "array" });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    // 转成 JSON（每行一个对象，键是表头）
    const json = XLSX.utils.sheet_to_json(worksheet, { defval: null });
    parsedData.value = json;
    console.log("解析后 JSON 数据：", json);
    gettableDataOrigin02(json);
  };
  reader.readAsArrayBuffer(file);
};

const gettableDataOrigin02 = data => {
  console.log(data);
  let arr = [];
  data.forEach(element => {
    if (element["类型"] && element["类型"].length == 1) roleType.value = element["类型"];

    const name = element["套装"];
    const eleArr = element["副属性编号"]?.split("-") || [];
    const SubAttribute = eleArr.filter(item => item !== "").map(Number);

    const SacredRelicNameArr = element["套装"]?.split("、") || [];
    const SandArr = element["沙"]?.split("/") || [];
    const cupArr = element["杯"]?.split("/") || [];
    const headArr = element["头"]?.split("/") || [];
    SacredRelicNameArr.forEach(itemRelic => {
      SandArr.forEach(itemSand => {
        cupArr.forEach(itemCup => {
          headArr.forEach(itemHead => {
            let SacredRelicId = -1;

            const Sand = itemSand.split("-")[1] - 0;
            const cup = itemCup.split("-")[1] - 0;
            const head = itemHead.split("-")[1] - 0;

            if (itemRelic.length === 3) {
              const str = itemRelic.substring(0, 2);
              const item = SacredRelicList.find(i => i.label.includes(str));
              SacredRelicId = item ? item.value : -1;
            }

            arr.push({
              name: element["角色"],
              roleType: roleType.value,
              SacredRelicName: itemRelic,
              SacredRelicId,
              Sand,
              cup,
              head,
              SubAttribute,
              Instructions: element["说明"] || ""
            });
          });
        });
      });
    });
  });

  console.log("--------------------------------------------");
  console.log("下面是生成的角色JSON数据(千万不要删除注释)：");
  console.log(arr);
  console.log("--------------------------------------------");
  ElMessage({
    message: "角色的json数据，按F12看控制台的内容",
    type: "success"
  });
};

const checkUseStatus = () => {
  const obj = {};

  tableDataOrigin.forEach(item => {
    if (item.SacredRelicId) {
      if (obj[item.SacredRelicId]) {
        if (!obj[item.SacredRelicId].includes(item.name)) {
          obj[item.SacredRelicId].push(item.name);
        }
      } else {
        obj[item.SacredRelicId] = [];
        obj[item.SacredRelicId].push(item.name);
      }
    }
  });
  const sortedEntries = Object.entries(obj).sort((a, b) => b[1].length - a[1].length); // 降序排列（长的在前）
  sortedEntriesData.value = sortedEntries;
  console.log(sortedEntriesData.value);
};

// 方法 1：普通遍历查找
const getValueByLabel = (label: string) => {
  if (label.length > 3) return "-1";
  const str = label.substring(0, 2);
  const item = SacredRelicList.find(i => i.label.includes(str));
  let val = item?.value + "";
  if (!val) val = "-1";
  if (parseInt(val) > 0 && parseInt(val) < 10) {
    val = "0" + val;
  }
  return val; // 如果找不到返回 null
};

const getTitle = (label: string) => {
  const item = SacredRelicList.find(i => i.label.includes(label.substring(0, 2)));
  if (item) {
    return `两件套效果：${item.twoPieceSet}<br>四件套效果：${item.fourPieceSet}`;
  } else {
    return "未找到对应的圣遗物信息";
  }
};

onMounted(() => {
  checkUseStatus();
  tableData.value = tableDataOrigin;
});

defineOptions({
  name: "fight"
});
</script>

<template>
  <div>
    <div class="mb-5 flex gap-2 flex-wrap">
      <el-select v-model="fromParams.role" multiple clearable filterable placeholder="请选择角色" style="width: 500px">
        <el-option v-for="item in RolesList" :key="item.value" :label="item.label" :value="item.label" />
      </el-select>
      <el-select v-model="fromParams.SacredRelicId" clearable filterable placeholder="请选择圣遗物" style="width: 240px">
        <el-option v-for="item in SacredRelicList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="fromParams.type" clearable filterable placeholder="元素类型" style="width: 240px">
        <el-option v-for="item in TypeList" :key="item.value" :label="item.label" :value="item.label" />
      </el-select>
      <el-select v-model="fromParams.sand" clearable placeholder="时之沙主属性" style="width: 240px">
        <el-option v-for="item in SandAttributeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="fromParams.cup" clearable placeholder="空之杯主属性" style="width: 240px">
        <el-option v-for="item in CupAttributeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="fromParams.head" clearable placeholder="理之冠主属性" style="width: 240px">
        <el-option v-for="item in headAttributeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="fromParams.SubAttribute" multiple clearable placeholder="请选择副属性" style="width: 400px">
        <el-option v-for="item in SubAttributeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="fromParams.NoSubAttribute" multiple clearable placeholder="请选择不要副属性" style="width: 400px">
        <el-option v-for="item in SubAttributeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>
    <div class="mb-5">
      <input ref="fileEleRef" type="file" hidden accept=".xlsx, .xls" @change="onFileChange" />
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="success" @click="clearAll">清空</el-button>
      <el-button type="primary" class="ml-5" @click="fileEleRef.click()">上传角色文件02</el-button>
      <el-button type="success" @click="dialogTableVisible = true">查看使用情况</el-button>
    </div>

    <!-- ✅ 表格部分 -->
    <el-table :data="pagedData" style="width: 100%; height: calc(100vh - 240px); overflow: auto">
      <!-- <el-table-column prop="Id" label="Id" /> -->
      <el-table-column prop="name" label="名字" width="100" />
      <el-table-column prop="SacredRelicId" label="圣遗物" width="150">
        <template #default="{ row }">
          <el-tooltip class="box-item" effect="dark" placement="top-start">
            <template #content>
              <div v-html="getTitle(row.SacredRelicName)" />
            </template>
            <el-tag :class="'color' + getValueByLabel(row.SacredRelicName)">
              {{ row.SacredRelicName }}
            </el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="roleType" label="属性" width="70">
        <template #default="{ row }">
          <el-tag :class="TypeListColor[row.roleType]">{{ row.roleType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="Sand" label="沙" width="130">
        <template #default="{ row }">
          <el-tag :class="colorList[row.Sand - 1]">{{ SandAttributeList[row.Sand - 1].label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="cup" label="杯" width="130">
        <template #default="{ row }">
          <el-tag :class="colorList[row.cup - 1]">{{ CupAttributeList[row.cup - 1].label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="head" label="头" width="130">
        <template #default="{ row }">
          <el-tag :class="headColorList[row.head - 1]">{{ headAttributeList[row.head - 1].label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="SubAttribute" label="副属性" width="500">
        <template #default="{ row }">
          <span v-for="item in row.SubAttribute" :key="item">
            <el-tag :class="subColorList[item - 1]" style="margin: 5px 2px">{{ SubAttributeList[item - 1].label }}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="Instructions" label="说明" />
    </el-table>

    <!-- ✅ 分页组件 -->
    <div v-if="pagedData.length > 0" class="page-sty">
      <el-pagination
        background
        layout="prev, pager, next, sizes, total"
        :total="tableData.length"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="pageSize = $event"
        @current-change="currentPage = $event"
      />
    </div>

    <el-dialog v-model="dialogTableVisible" title="圣遗物使用情况" width="800">
      <div>
        <div v-for="(item, index) in sortedEntriesData" :key="index">
          <h3>
            <span class="mr-5 text-xl">排名：{{ index + 1 }}</span>
            <span v-if="item[0] == '-1'">圣遗物：2 + 2</span>
            <span v-else
              >圣遗物：<span class="text-blue-500">{{ SacredRelicList[item[0] - 1].label }}</span></span
            >
          </h3>
          <div class="mt-1 mb-1">
            使用角色：<span class="text-red-500">{{ item[1].join("，") }}</span>
          </div>
          <div class="mb-4">
            使用角色数量：<span class="text-cyan-700 font-bold">{{ item[1].length }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
